package com.hysoft.web.config;

import com.alibaba.fastjson2.JSON;
import com.hysoft.common.result.Result;
import com.hysoft.web.annotation.IgnoreResponseAdvice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * <h1>实现统一响应</h1>
 *
 * @author 王天瑞
 * @since 1.0
 * @version 1.0
 */
@RestControllerAdvice(value = "com.hysoft")
@Slf4j
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * <h2>判断是否需要对响应进行处理</h2>
     *
     * @param methodParameter 请求方法对象
     * @param converterType 处理类
     * @return 是否需要进行响应处理
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> declaringClass = methodParameter.getDeclaringClass();
        Method method = methodParameter.getMethod();
        Class<IgnoreResponseAdvice> type = IgnoreResponseAdvice.class;
        return !(declaringClass.isAnnotationPresent(type) || Objects.requireNonNull(method).isAnnotationPresent(type));
    }

    /**
     * <h2>对请求响应结果进行封装</h2>
     *
     * @param body 原生返回数据值
     * @param returnType 返回类型
     * @param selectedContentType 用不到
     * @param selectedConverterType 用不到
     * @param request 用不到
     * @param response 用不到
     * @return 请求响应结果
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Result<Object> result = Result.ok();
        if (body instanceof Result) {
            return body;
        }
        result.setData(body);
        if (body instanceof String) {
            return JSON.toJSONString(result);
        }
        return result;
    }

    /**
     * <h2>未定义异常</h2>
     * @param e 异常对象
     * @return 异常处理结果
     */
    @ExceptionHandler(value = Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error("请求响应异常!", e);
        return Result.failed();
    }
}
